<template>
  <div style="height: calc(100vh - 75px);">
    <div style="margin-top: 10px;display: flex;">
      <div style="width: 20px;"></div>
      <div style="height: 40px;width: 40px;">
        <input
            type="file"
            ref="fileInput"
            style="display: none"
            @change="handleFileChange"
        />
        <button @click="triggerFileInput">导入任务</button>

      </div>
      <div style="margin-left: 100px;">
        <JButton @click="add">新增一条任务</JButton>
        <JButton @click="doDel">批量删除任务</JButton>
        <JButton @click="downmoban">下载任务模板</JButton>
        <JButton @click="batchStop" type="info">批量停止</JButton>
        <!--            <JButton @click="sendMessage">send</JButton>-->
      </div>
      <div style="text-align: center;width: 260px;margin: 0 auto;user-select: none;" >
        <JTab v-model="tabindex" :list="[
            {name: '进行中', id: 'running'},
            {name: '已完成', id: 'done'},
            {name: '已停止', id: 'stop'},
          ]" @change="changeTab" />
      </div>
    </div>
    <div style="margin-left: 10px;margin-top: 20px;">
      <XForm v-model="model" :rules="rules" />
    </div>
    <div style="margin-top: 10px;">
      <JGrid ref="jgridRef"
             :passList="passList"
             size="small"
             :offset-width="2"
             :offset-bottom="170"
             show-footer
             show-pager
             :page-size="200"
             :search-model="model" listUrl="app/py"
             :columns="columns" />
    </div>
  </div>
  <tiny-dialog-box  v-model:visible="showmoban">
    <div>选择的日期会在模板中自动填充日期,表示任务执行的时间段</div>
    <div style="height: 10px;"></div>
    <JPicker style="width: 200px;" placeholder="开始日期" v-model="beginDate" clearable></JPicker>
    <div style="height: 10px;"></div>
    <JPicker style="width: 200px;" placeholder="结束日期" v-model="endDate" clearable></JPicker>
    <div style="height: 30px;"></div>
    <JButton @click="doDownMoban">生成并下载模板</JButton>
    <div style="height: 50px;"></div>
  </tiny-dialog-box>
</template>
<script setup>
import {computed, onMounted, onUnmounted, ref, watch, nextTick} from "vue";
import tool from "@/utils/tool";
import {TinyDialogBox} from "@opentiny/vue";
import {useRoute} from "vue-router";
const model = ref({
  which:'taskList',
  usernameAss: '',
  stat: 'running'
})
const route = useRoute()
const username = ref('')
const jgridRef = ref(null)
const passList = ref([])
const tabindex = ref('running')
const beginDate = ref('')
const endDate = ref('')
const showmoban = ref(false)
onMounted(() => {
  if(typeof route.query !== 'undefined' && route.query.username) {
    username.value = route.query.username
    tool.data.set('usernameAss', route.query.username)
    model.value.usernameAss = username.value
    getList()
  }
})
const getList = () => {
  jgridRef.value.getList()
}
const rules = [
  {field: 'beginDate', title: '开始日期', com: 'JPicker', width: 220,clearable: true,placeholder: '开始'},
  {field: 'endDate', title: '结束日期', com: 'JPicker', width: 220,clearable: true,placeholder: '结束'},
  {field: 'buName',idField: 'buId', title: '终端', com: 'JAuto', width: 250,cat: 'py_ter',url:'app/py'},
  {field: 'invName',idField: 'invId', title: '商品', com: 'JAuto', width: 250,cat: 'py_good',url:'app/py'},
  {field: '',idField: '',  com: 'JButton', width: 100,text: '查询',icon:'search',
    events: {
      click:() => {
        doSearch()
      }
    }
  }
]
const columns = ref([
  {type:'index',width: 60},
  {type:'selection',width: 60},
  {title:'状态',field:'stat', width: 120,headerAlign:'center',align: 'center'},
  {title:'开始日期',field:'beginDate', width: 100,align:'center',},
  {title:'结束日期',field:'endDate', width: 100,align:'center',},
  {title:'终端名称',field:'buName', width: 220,headerAlign:'center',},
  {title:'商品名称',field:'invName', width: 220,headerAlign:'center',},
  {title:'单价',field:'price', width: 80,headerAlign:'center',align: 'center',formatter:'formatQty'},
  {title:'出到通用数量',field:'qty', width: 100,align: 'right',headerAlign:'center',formatter:'formatQty',sum:true},
  {title:'(完成)',field:'qtyDone', width: 120,align: 'right',headerAlign:'center',formatter:'formatQty',sum:true},
  {title:'出到现饮数量',field:'terType1', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'(完成)',field:'terType1Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'出到非现饮数量',field:'terType2', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'(完成)',field:'terType2Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'出到赠酒数量',field:'send', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'(完成)',field:'sendDone', width: 100,headerAlign:'center',align: 'right',formatter:'formatQty',sum:true},
  {title:'备注',field:'remark', width: 120,headerAlign:'center',align: 'center'},
  {
    title: '操作',width: 200,
    btns: [
      {label: '修改',show: "row.stat==='正常'",click: (row) => { alt(row) }},
      {label: '停止任务',show: "row.stat==='正常'",click: (row) => {
          tool.confirm('确定停止').then(() => {
            tool.post('app/py', {id: row.id, which:'stopOneTask', usernameAss: username.value}).then(ret => {
              if(ret.stat) getList()
            })
          })
        }},
      {label: '删除',show: "row.stat==='正常'",click: (row) => {
          tool.confirm('确定删除').then(() => {
            tool.post('app/py', {id: row.id, which:'delOneTask', usernameAss: username.value}).then(ret => {
              if(ret.stat) getList()
            })
          })
        }},
    ]
  }
])
const batchStop = () => {
  let list = jgridRef.value.getSelect()
  if(list.length === 0) return tool.err('请选中行')
  tool.confirm('确定停止'+list.len).then(() => {
    let ids = []
    for (let i = 0; i < list.length; i++) {
      ids.push(list[i].id)
    }
    tool.post('app/py', {ids: ids, which:'stopBatchTask', usernameAss: username.value}).then(ret => {
      if(ret.stat) getList()
    })
  })

}
const downmoban = () => {
  beginDate.value = tool.getDay()
  endDate.value = ''
  showmoban.value = true
}
const message = ref('');
const file = ref(null);
// 处理文件选择

const fileInput = ref(null);
const triggerFileInput = () => {
  fileInput.value.click(); // 手动触发文件选择框
}
const handleFileChange = (event) => {
  file.value = event.target.files[0] // 获取选择的文件
  if (file.value) {
    uploadFile() // 自动上传文件
  }
}

// 上传文件
const uploadFile = async () => {
  if (!file.value) {
    return tool.err('请先选择文件')
  }

  try {
    const formData = new FormData()
    formData.append('file', file.value); // 将文件添加到 FormData
    tool.post('app/upload', formData,true, 'multipart/form-data').then(ret => {
      if(ret.stat && ret.data) {
        file.value = null
        fileInput.value.value = ''
        tool.post('app/py',{which: 'addTask',usernameAss:username.value, formData: {filename: ret.data}}).then(ret => {
          if(ret.stat) {
            getList()
          }
        })
      }
    })
  } catch (error) {
    file.value = null
    fileInput.value.value = ''
    tool.err('上传失败')
  }
}

const changeTab = (tab) => {
  model.value.stat = tab
  if(tab === 'running') {
    columns.value = [
      {type:'index',width: 60},
      {type:'selection',width: 60},
      {title:'状态',field:'stat', width: 120,headerAlign:'center',align: 'center'},
      {title:'开始日期',field:'beginDate', width: 100,align:'center',},
      {title:'结束日期',field:'endDate', width: 100,align:'center',},
      {title:'终端名称',field:'buName', width: 220,headerAlign:'center',},
      {title:'商品名称',field:'invName', width: 220,headerAlign:'center',},
      {title:'单价',field:'price', width: 80,headerAlign:'center',align: 'center',formatter:'formatZero'},
      {title:'出到通用数量',field:'qty', width: 100,align: 'right',headerAlign:'center',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'qtyDone', width: 120,align: 'right',headerAlign:'center',formatter:'formatZero',sum:true},
      {title:'出到现饮数量',field:'terType1', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'terType1Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'出到非现饮数量',field:'terType2', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'terType2Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'出到赠酒数量',field:'send', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'sendDone', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'备注',field:'remark', width: 120,headerAlign:'center',align: 'center'},
      {
        title: '操作',width: 200,
        btns: [
          {label: '修改',show: "row.stat==='正常'",click: (row) => { alt(row) }},
          {label: '停止任务',show: "row.stat==='正常'",click: (row) => {
              tool.confirm('确定删除').then(() => {
                tool.post('app/py', {id: row.id, which:'stopOneTask', usernameAss: username.value}).then(ret => {
                  if(ret.stat) getList()
                })
              })
            }},
          {label: '删除',show: "row.stat==='正常'",click: (row) => {
              tool.confirm('确定删除').then(() => {
                tool.post('app/py', {id: row.id, which:'delOneTask', usernameAss: username.value}).then(ret => {
                  if(ret.stat) getList()
                })
              })
            }},
        ]
      }
    ]
  }
  else {
    columns.value = [
      {type:'index',width: 60},
      {type:'selection',width: 60},
      {title:'状态',field:'stat', width: 120,headerAlign:'center',align: 'center'},
      {title:'开始日期',field:'beginDate', width: 100,align:'center',},
      {title:'结束日期',field:'endDate', width: 100,align:'center',},
      {title:'终端名称',field:'buName', width: 220,headerAlign:'center',},
      {title:'商品名称',field:'invName', width: 220,headerAlign:'center',},
      {title:'单价',field:'price', width: 80,headerAlign:'center',align: 'center',formatter:'formatZero'},
      {title:'出到通用数量',field:'qty', width: 100,align: 'right',headerAlign:'center',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'qtyDone', width: 120,align: 'right',headerAlign:'center',formatter:'formatZero',sum:true},
      {title:'出到现饮数量',field:'terType1', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'terType1Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'出到非现饮数量',field:'terType2', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'terType2Done', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'出到赠酒数量',field:'send', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'(完成)',field:'sendDone', width: 100,headerAlign:'center',align: 'right',formatter:'formatZero',sum:true},
      {title:'备注',field:'remark', width: 120,headerAlign:'center',align: 'center'},
    ]
  }
  nextTick(() => {
    jgridRef.value.setCols()
    getList()
  })
}
const add = () => {
  let options = {
    title: '新增一条任务',
    width: 600,
    height: 350,
    rules: [
      {field: 'beginDate',com: 'JPicker', title: '开始日期',defaultValue: tool.getDay()},
      {field: 'endDate',com: 'JPicker', title: '结束日期'},
      // {field: 'terType',idField:'terType',com: 'JAuto', title: '终端类型',list:[{id:'现饮',name:'现饮'},{id:'非现饮',name:'非现饮'}]},
      {field: 'buName',idField:'buId',com: 'JAuto', title: '终端名称',cat: 'py_ter',url:'app/py'},
      {field: 'invName',idField:'invId',com: 'JAuto', title: '商品名称',cat: 'py_good',url:'app/py'},
      {field: 'price',com: 'JInput', title: '商品价格'},
      {field: 'qty',com: 'JInput', title: '出到通用数量'},
      {field: 'terType1',com: 'JInput', title: '出到现饮数量'},
      {field: 'terType2',com: 'JInput', title: '出到非现饮数量'},
      {field: 'send',com: 'JInput', title: '出到赠品数量'},

      {field: 'remark',com: 'JInput', title: '备注'},
    ],
    btns:[
      {name: '保存并关闭',click:(api,close) =>{
          tool.post('app/py', {which:'saveOneTask',formData: api.getFormData()}, true).then(ret => {
            if(ret.stat) {
              close()
              getList()
            }
          })
        }},
    ]
  }
  tool.editor(options)
}

const doDownMoban = () => {
  if(beginDate.value && endDate.value) {
    // send('getMoban,'+beginDate.value+','+endDate.value);
    tool.post('app/py',{usernameAss: username.value, which: 'taskmoban', formData: {beg:beginDate.value, end:endDate.value}},true).then(ret => {
      if(ret.stat) {
        // window.open(ret.data)
        if(typeof qt !== 'undefined') {
          new QWebChannel(qt.webChannelTransport, function (channel) {
            // 获取 Python 中注册的对象
            window.bridge = channel.objects.bridge;
            let send = {
              name: "download",
              url: ret.data
            }
            window.bridge.send_message(JSON.stringify(send), function (response) {

            })
          });
        }
        // showmoban.value = false
        setTimeout(() => {
          showmoban.value = false
        }, 500)
      }
    })
  }
  else {
    return tool.err('请选择日期')
  }
}
const doDel = () => {
  let list = jgridRef.value.getSelect()
  let ids = []
  list.map(row => {
    ids.push(row.id)
  })
  if(ids.length > 0) {
    tool.post('app/py', {usernameAss: username.value, ids, which: 'delBatchTask'}).then(ret => {
      if(ret.stat) getList()
    })
  }
  else {
    tool.err('没有选中要删除的行')
  }
}

const doSearch = () => {
  getList()
}
const alt = (row) => {
  let options = {
    title: '修改任务',
    width: 600,
    height: 350,
    rules: [
      {field: 'beginDate',com: 'JPicker', title: '开始日期',disabled: true},
      {field: 'endDate',com: 'JPicker', title: '结束日期',disabled: true},
      {field: 'buName',idField:'buId',com: 'JAuto', title: '终端名称',disabled: true},
      {field: 'invName',idField:'invId',com: 'JAuto', title: '商品名称',disabled: true},
      {field: 'price',com: 'JInput', title: '商品价格',disabled: true},
      {field: 'qty',com: 'JInput', title: '出到通用数量'},
      {field: 'terType1',com: 'JInput', title: '出到现饮数量'},
      {field: 'terType2',com: 'JInput', title: '出到非现饮数量'},
      {field: 'send',com: 'JInput', title: '出到赠品数量'},

      {field: 'remark',com: 'JInput', title: '备注'},
    ],
    model: row,
    btns:[
      {name: '保存并关闭',click:(api,close) =>{
          tool.post('app/py', {which:'saveOneTask',formData: api.getFormData()}, true).then(ret => {
            if(ret.stat) {
              close()
              getList()
            }
          })
        }},
    ]
  }
  tool.editor(options)
}

const changeList = () => {
   getList()
}

defineExpose({changeList})
</script>
<style scoped lang="scss">
:deep(.input-label) {
  width: 40px !important;
  height: 40px !important;
}
</style>